package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.ServletUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充..." );
        this.strictInsertFill(metaObject, "createBy" , String.class, getUserId());
        this.strictInsertFill(metaObject, "createTime" , Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充..." );
//        this.strictInsertFill(metaObject, "updateUserId", Long.class, 123456L);
//        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.setFieldValByName("updateBy" , getUserId(), metaObject);
        this.setFieldValByName("updateTime" , new Date(), metaObject);
    }

    private String getUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtils.isNotEmpty(loginUser)) {
            return String.valueOf(loginUser.getUserId());
        } else {
            throw new RuntimeException("获取登录状态错误" );
        }
    }
}